//
//  ViewController.swift
//  WKWebView
//
//  Created by MoneyLee on 2020/8/28.
//  Copyright © 2020 MoneyLee. All rights reserved.
//

import UIKit
import WebKit

class ViewController: UIViewController {

    let progress = Progress()
    
    var webView: WKWebView!
    
    let spinner = UIActivityIndicatorView(style: .whiteLarge)
    
    //自定义根视图
    override func loadView() {
        let config = WKWebViewConfiguration()
        //默认允许使用airplay播放
        //config.allowsAirPlayForMediaPlayback = true
        //默认不允许使用html自带播放器 使用苹果的AVPlayer
        //config.allowsInlineMediaPlayback = false
        //默认允许画中画模式(ipad)
        //config.allowsPictureInPictureMediaPlayback = true
        //网页内的手机号,链接,地址等数据自动识别
        //config.dataDetectorTypes = [.all]
        
//        let preferences = WKPreferences()
//        preferences.javaScriptEnabled = true
//        preferences.minimumFontSize = 0
//        config.preferences = preferences
        
        //配置需要从服务端接收的数据key
        config.userContentController.add(self, name: "user")
        //html页面js的处理
//        <script type="text/javascript">
//            function sendMessageToiOS(){
//                var lebus = {
//                    name: "lebus",
//                    age:20
//                }
//                window.webkit.messageHandlers.user.postMessage(lebus)
//            }
//        </script>
        
        webView = WKWebView(frame: .zero, configuration: config)
        webView.allowsBackForwardNavigationGestures = true
        webView.uiDelegate = self
        webView.navigationDelegate = self
        view = webView
        
        webView.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: .new, context: nil)
        
        
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == #keyPath(WKWebView.estimatedProgress) {
            print(webView.estimatedProgress)
        }
    }
    
    deinit {
        webView.removeObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress))
    }
        
    override func viewDidLoad() {
        super.viewDidLoad()
        setSpinner()
        /**
         *  可以手动触发的一些方法
         */
        //加载中
//        webView.isLoading
        //重新加载
//        webView.reload()
        //重新加载跳过缓存
//        webView.reloadFromOrigin()
        //停止加载
//        webView.stopLoading()
        //返回上一页
//        webView.goBack()
        //返回下一页
//        webView.goForward()
        
        webView.backForwardList
        
        //加载
        webView.load("http://www.baidu.com")
        
//        handleHTMLString()
//        handleHTMLFile()
        
    }


}


extension ViewController: WKNavigationDelegate {
    
    //请求前的拦截
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        print("-------------- \n")
        print("请求的拦截: \(navigationAction.request.url?.host)")
        print("请求的拦截: \(navigationAction.request.url?.absoluteString)")
        print("-------------- \n")
        decisionHandler(.allow)
    }
    
    //开始请求
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        print(#function)
        spinner.startAnimating()
    }
    
    //在接收服务端返回内容的时候拦截
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        if let httpRespone = navigationResponse.response as? HTTPURLResponse {
            if httpRespone.statusCode == 200 {
                decisionHandler(.allow)
            }
        }else {
            decisionHandler(.cancel)
        }
    }
    
    
    //开始接收服务器端内容
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        print(#function)
    }
    //加载完毕
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print(#function)
        spinner.stopAnimating()
        handleJS()
    }
    //请求失败
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        print(#function)
        spinner.stopAnimating()
    }
    
    func setSpinner() {
        spinner.backgroundColor = UIColor.black
        spinner.layer.cornerRadius = 10
        spinner.layer.masksToBounds = true
        spinner.translatesAutoresizingMaskIntoConstraints = false
        webView.addSubview(spinner)
        spinner.centerXAnchor.constraint(equalTo: webView.centerXAnchor).isActive = true
        spinner.centerYAnchor.constraint(equalTo: webView.centerYAnchor).isActive = true
        spinner.widthAnchor.constraint(equalToConstant: 80).isActive = true
        spinner.heightAnchor.constraint(equalToConstant: 80).isActive = true
    }
    
    func handleHTMLString() {
        let html = """
            <!DOCTYPE html>
            <html lang="en">
            <head>
            <meta charset="UTF-8">
            <title>Lebus</title>
            </head>
            <body>
            <div style="text-align: center;font-size: 80px;margin-top: 350px">Lebus的iOS教程</div>
            </body>
            </html>
            """
        webView.loadHTMLString(html, baseURL: Bundle.main.resourceURL)
        
    }
    
    func handleHTMLFile() {
        let url = Bundle.main.url(forResource: "HomePage", withExtension: "html")!
        //allowingReadAccessTo 资源路径 取当前URL上级
        webView.loadFileURL(url, allowingReadAccessTo: (url.deletingLastPathComponent()))
    }
    
    func handleJS() {
        webView.evaluateJavaScript("document.body.offsetHeight") { (res, error) in
            print(res)
        }
    }
    
    //截屏操作
    func takeSnapShot() {
        //with: nil 截全屏
        //配置截取的区域
        let config = WKSnapshotConfiguration()
        config.rect = CGRect(x: 0, y: 0, width: 200, height: 200)
        webView.takeSnapshot(with: nil) { (image, error) in
            guard let img = image else {return}
            //存取到用户相册
        }
    }
    
    //读取cookie 删除cookie
    func handleCookie() {
        webView.configuration.websiteDataStore.httpCookieStore.getAllCookies { (cookies) in
            for cookie in cookies {
                print(cookie.name)
                if cookie.name == "auth" {
                    self.webView.configuration.websiteDataStore.httpCookieStore.delete(cookie) {
                        
                    }
                } else {
                    print(cookie.value)
                }
            }
        }
    }
    
}






//用户将网页弹窗转换成原生弹窗 alert confirm prompt
extension ViewController: WKUIDelegate {
    
    //警告弹窗
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        
        let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "确定", style: .default, handler: { (_) in
            completionHandler()
        }))
        present(alert, animated: true, completion: nil)
    }
    
    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
        
        let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { (_) in
            completionHandler(false)
        }))
        alert.addAction(UIAlertAction(title: "确定", style: .default, handler: { (_) in
            completionHandler(true)
        }))
        present(alert, animated: true, completion: nil)

    }
    
    func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
        
        let alert = UIAlertController(title: nil, message: prompt, preferredStyle: .alert)
        alert.addTextField { (textFiled) in
            textFiled.placeholder = defaultText
        }
        alert.addAction(UIAlertAction(title: "确定", style: .default, handler: { (_) in
            completionHandler(alert.textFields?.first?.text)
        }))
        present(alert, animated: true, completion: nil)

    }
    
}

//和JS交互
extension ViewController: WKScriptMessageHandler {
    
    //获取html js传递过来的数据
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if message.name == "user" {
            print(message.body)
        }
    }
    
    
    
    
}
